package jsu.ljy.lostandfind.controller;

import jsu.ljy.lostandfind.common.Result;
import jsu.ljy.lostandfind.model.User;
import jsu.ljy.lostandfind.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理控制器
 * 
 * <p>处理用户相关的HTTP请求，包括用户登录、注册、注销等操作。</p>
 * 
 * @author 罗嘉毅
 * @version 1.0
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * 
     * @param loginData 登录信息，包含用户名和密码
     * @param session HTTP会话
     * @return 登录用户信息
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map<String, String> loginData, HttpSession session) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        
        // Validate input parameters
        if (username == null || username.trim().isEmpty()) {
            return Result.error(400, "用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            return Result.error(400, "密码不能为空");
        }
        
        try {
            User user = userService.login(username, password);
            if (user != null) {
                // Create a new User object without password for session storage
                User sessionUser = new User();
                sessionUser.setId(user.getId());
                sessionUser.setUsername(user.getUsername());
                sessionUser.setPhone(user.getPhone());
                sessionUser.setEmail(user.getEmail());
                sessionUser.setCreateTime(user.getCreateTime());
                
                session.setAttribute("currentUser", sessionUser);
                return Result.success(sessionUser);
            }
            return Result.error(401, "用户名或密码错误");
        } catch (IllegalArgumentException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 用户注册
     * 
     * @param user 用户注册信息
     * @return 注册成功的用户信息（不含密码）
     * @throws IllegalArgumentException 当用户信息不完整或用户名已存在时抛出
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        try {
            // 设置创建时间
            user.setCreateTime(new Date());
            
            // 注册用户
            userService.register(user);
            
            // 清空敏感信息
            user.setPassword(null);
            
            return Result.success(user);
        } catch (IllegalArgumentException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "注册失败：" + e.getMessage());
        }
    }

    @PostMapping("/logout")
    public Result<Void> logout(HttpSession session) {
        session.invalidate();
        return Result.success(null);
    }

    @GetMapping("/current")
    public Result<User> getCurrentUser(HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        return Result.success(currentUser);
    }

    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.error(404, "用户不存在");
    }
} 